"""
asyncio同步和通信

asyncio不需要锁（单线程）
"""

import asyncio
import aiohttp
from asyncio import Lock, Queue

cache = {}
lock = Lock()


async def get_stuff(url):
    # 使用锁（同步机制）
    async with lock:
        if url in cache:
            return cache[url]

        stuff = aiohttp.request("GET", url)
        cache[url] = stuff
        return stuff


async def parse_stuff():
    url = "http://shop.projectsedu.com/goods/{}/".format(1)
    stuff = await get_stuff(url)


async def use_stuff():
    url = "http://shop.projectsedu.com/goods/{}/".format(1)
    stuff = await get_stuff(url)


def use_asyncio():
    tasks = [parse_stuff(), use_stuff()]
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()


if __name__ == '__main__':
    use_asyncio()
